import { viteCommonjs } from '@originjs/vite-plugin-commonjs'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path from 'path'
import { defineConfig } from 'vite'
import envCompatible from 'vite-plugin-env-compatible'
import { createHtmlPlugin } from 'vite-plugin-html'
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'
import prefixer from 'postcss-prefix-selector';
import autoprefixer from 'autoprefixer';
import vappConf from './AssetPack/vapp-meta-data.json'
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import VappMeta from './AssetPack/vapp-meta-data.json';
const configUtil = require('./vapp-helper/configUtil.ts')

const allProxy = configUtil.getAllEnvProxy(
  {
    '/auth': {},
    '/quality': {},
    '/dcp': {},
    '/iam': {},
    '/api-manager': {},
  },
)

// https://vitejs.dev/config/
const componentsViteConfig = {
  define: {
    'process.env.NODE_ENV': process.env.NODE_ENV === 'development' ? JSON.stringify('development') : JSON.stringify('production'),
    'process.env.project_folder': JSON.stringify(path.basename(__dirname)),
    'process.env.xvueNameSpace': JSON.stringify(VappMeta.xvueNameSpace),
    'process.env.xvueNameSpace_': JSON.stringify(`${VappMeta.xvueNameSpace.replace(/-/g, '_')}_`),
  },
  resolve: {
    alias: [
      {
        find: /^~/,
        replacement: '',
      },
      {
        find: '@',
        replacement: path.resolve(__dirname, 'src'),
      },
      {
        find: 'lib',
        replacement: path.resolve(__dirname, 'lib'),
      },
    ],
    extensions: [
      '.mjs',
      '.js',
      '.ts',
      '.jsx',
      '.tsx',
      '.json',
      '.vue',
    ],
  },
  plugins: [
    vue(),
    vueJsx(),
    viteCommonjs(),
    envCompatible(),
    cssInjectedByJsPlugin(),
    createHtmlPlugin({
      inject: {
        data: {
          title: 'componentsDemo',
        },
      },
    }),
    AutoImport({
      imports: ['vue', 'vue-router', 'vue-i18n'],
      dts: './types/auto-imports.d.ts',
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      deep: true,
      dts: './types/components.d.ts',
      resolvers: [ElementPlusResolver()],
    }),
  ],
  base: '/',
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
    postcss: {
      plugins: [
        prefixer({
          prefix: `.${vappConf.xvueNameSpace}`,
          exclude: [`.${vappConf.xvueNameSpace}`],
          transform(prefix, selector, prefixedSelector, filePath, rule) {
            // 开发环境不执行添加前缀功能
            if (process.env.NODE_ENV === 'development') {
              return selector
            }
            if (filePath.match(/node_modules/)) {
              return selector // Do not prefix styles imported from node_modules
            }
            return prefixedSelector
          },
        }),

        autoprefixer({}) // add options if needed
      ],
    }
  },
  server: {
    strictPort: false,
    port: 8068,
    host: 'localhost.huawei.com',
    open: true,
    proxy: allProxy,
  },
  commonjsOptions: {
    esmExternals: true,
  },
  build: {
    minify: false,
    lib: {
      name: 'componentsDemo',
      entry: path.resolve(__dirname, 'src/components/index-old.js'),
      formats: ['umd'],
      fileName: format => {
        return 'componentsDemo.umd.min.js'
      },
    },
    rollupOptions: {
      external: ['vue', 'element-plus', 'element-plus/es', 'vuex', 'vue-router', 'axios', 'echarts', 'xe-utils', 'vxe-table'],
      output: {
        dir: './AssetPack/web/web-components/lib',
        globals: {
          vue: 'Vue',
          'element-plus': 'ElementPlus',
          'element-plus/es': 'ElementPlus',
          vuex: 'Vuex',
          'vue-router': 'VueRouter',
          axios: 'axios',
          echarts: 'echarts',
          'xe-utils': 'XEUtils',
          'vxe-table': 'VXETable',
          'echarts-liquidfill': 'echarts-liquidfill',
        },
        inlineDynamicImports: true,
        name: 'componentsDemo',
        exports: 'named',
      },
    },
    commonjsOptions: {
      includes: ['node_modules/**/**.js'],
      transfromMixedEsModules: true,
    },
  },
}

// 关于页面的vite配置，本就是我从组件那边复制过来进行修改的，或许还有待简化和完善，如果伙伴们有更好的想法和建议，也欢迎一同交流和进步
const pagesViteConfig = {
  define: {
    'process.env.NODE_ENV': process.env.NODE_ENV === 'development' ? JSON.stringify('development') : JSON.stringify('production'),
    'process.env.project_folder': JSON.stringify(path.basename(__dirname)),
    'process.env.xvueNameSpace': JSON.stringify(VappMeta.xvueNameSpace),
    'process.env.xvueNameSpace_': JSON.stringify(`${VappMeta.xvueNameSpace.replace(/-/g, '_')}_`),
  },
  resolve: {
    alias: [
      {
        find: /^~/,
        replacement: '',
      },
      {
        find: '@',
        replacement: path.resolve(__dirname, 'src'),
      },
      {
        find: 'lib',
        replacement: path.resolve(__dirname, 'lib'),
      },
    ],
    extensions: [
      '.mjs',
      '.js',
      '.ts',
      '.jsx',
      '.tsx',
      '.json',
      '.vue',
    ],
  },
  plugins: [
    vue(),
    vueJsx(),
    viteCommonjs(),
    envCompatible(),

    // cssInjectedByJsPlugin(), // 删除了才能正常请求图片资源
    createHtmlPlugin({
      inject: {
        data: {
          title: 'componentsDemo',
        },
      },
    }),
    AutoImport({
      imports: ['vue', 'vue-router', 'vue-i18n'],
      dts: './types/auto-imports.d.ts',
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      deep: true,
      dts: './types/components.d.ts',
      resolvers: [ElementPlusResolver()],
    }),
  ],
  base: './', // 页面和组件的根路由不一样
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
  },
  server: {
    strictPort: false,
    port: 8068,
    host: 'localhost.huawei.com',
    open: true,
    proxy: allProxy,
  },
  build: {
    minify: false,
    rollupOptions: {
      output: {
        dir: './AssetPack/web/web-pages/dist',
      },
    },
  },
}

const viteConfig = defineConfig( mode => {
  if (mode.mode === 'pages') {
    return pagesViteConfig
  }
  return componentsViteConfig
})

export default viteConfig